<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Member;
use app\model\StoreMember;
use app\model\RegisterField;

class StorememberController extends Base
{

	function index()
	{
		$weid = weid();
		$page = input('post.page', 1, 'intval');
        $limit = input('post.limit', 20, 'intval');
		$ptype = 'member';
		$Fielddata = RegisterField::where(['weid' => $weid, 'ptype' => $ptype])->select()->toArray();

		if (empty($Fielddata)) {
			RegisterField::datainitial($ptype);
		}

		$query = $this->setSearch();
		$res = $query->order('sort asc,id desc')
			->paginate(getpage())
			->toArray();
        $map = [
            'weid' => $weid,
            'sid' => $this->sid,
            'status' => 1
        ];
        $res['data'] = Member::where($map)->limit(($page - 1)*$limit, $limit)->order('id desc')->select();

		if (!empty($res['data'])) {
			foreach ($res['data'] as &$vo) {
				$vo = Member::conversion($vo);
			}
		}
		$data['data'] = $res;
		if ($page == 1) {
			$data['field_data']['RegisterField'] = RegisterField::getlistViewField($ptype);
		}

		return $this->json($data);
	}
	function setSearch()
	{
		$keyword = trim(input('post.keyword', '', 'serach_in'));
		$status = input('post.status', '', 'serach_in');
		$regdate = input('post.regdate', '', 'serach_in');
		$weid = weid();

		$where = [];

		$where['member.weid'] = (int) $weid;

		$withJoin = [
			'storemember' => explode(',', 'sid'),
		];

//        if( $this->sid > 0){
//            $where['member.sid'] = $this->sid;
//        }
		$query = Member::where($where)->withJoin($withJoin, 'left');

		$query->where(['storemember.sid' => $this->sid]);

		if (!empty($regdate)) {
			$query->where('member.regdate', 'between', [strtotime($regdate[0]), strtotime($regdate[1])]);
		}

		if (!empty($keyword)) {

			$query->where('member.nickname|member.telephone', 'like', '%' . $keyword . '%');
		}

		if (!empty($status) || $status === "0") {
			$query->where(['member.status' => $status]);
		}

		return $query;
	}
	function delete()
	{
		return $this->del(new StoreMember());
	}
}
